package com.partners.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.basic.*;
import com.partners.dao.bo.*;
import com.partners.dao.dto.DealOrderOutPutDTO;
import com.partners.model.BusinessException;
import com.partners.model.Paging;
import com.partners.service.OrderService;
import com.partners.service.UserService;
import com.partners.utils.CodeUtils;
import com.partners.utils.JsonUtils;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liangyongle
 * @date 2018-12-21
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

   @Resource
   private OrderDao orderDao;

   @Resource
   private CustomerDao customerDao;

   @Resource
   private ConfigDao configDao;

   @Resource
   private PointsLogDao pointsLogDao;

   @Resource
   private UserService userService;

   @Resource
   private UserDao userDao;


    /**
     * 获取我的订单列表
     * @param uid Integer
     * @return Object
     */
    @Override
    public Map<String, Object> getOrderList(Paging paging, Integer uid, Integer returnType) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String,Object>> list = orderDao.getOrderListByUserId(uid);
        Page page = (Page) list;
        Object total = page.getTotal();
        if(returnType == 1){
            Map<Object, List<Map<String, Object>>> timeList = JsonUtils.toMonthList(list);
            allList.put("list",timeList);
        }else{
            for (Map<String,Object> map : list){
                String timeFormat = "yyyy-MM-dd HH:mm:ss";
                String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),timeFormat);
                map.put("addtime",addtime);
            }
            allList.put("list",list);
        }

        return allList;
    }


    /**
     * 创建订单
     * @param orderDO OrderDO
     * @return boolean
     */
    @Override
    @Transactional
    public Integer createOrder(OrderDO orderDO) {
        //查询该客户是否存在
        CustomerDO customer = customerDao.selectByPrimaryKey(orderDO.getCustomerId());
        if(customer ==null){
            throw BusinessException.of(ErrorMessageEnum.CUSTOMER_NOT_FOUND);
        }
        ConfigDO configDO = configDao.selectByPrimaryKey(1);
        //查询客户是否已经过期了
        Integer nowTime = TimestampUtils.timestamp();
        if((nowTime - customer.getAddtime())/3600/24 > configDO.getIndate()){
            throw BusinessException.of(ErrorMessageEnum.CUSTOMER_IS_TIMEOVER);
        }
        //查询该客户是否已经下单了
        Integer exist = orderDao.selectOrderByCustomerId(orderDO.getCustomerId());
        if(exist !=null){
            throw BusinessException.of(ErrorMessageEnum.ORDER_IS_EXIST);
        }

        UserDO userDO1 = userDao.selectByPrimaryKey(customer.getUid());
        //订单号
        String orderNum = CodeUtils.createOrderNum();
        Long orderNo = Long.parseLong(orderNum);
        orderDO.setOrderNo(orderNo);
        orderDO.setUid(customer.getUid());
        orderDO.setAddtime(TimestampUtils.timestamp());
        Integer result = orderDao.insertSelective(orderDO);
        CustomerDO customerDO  = new CustomerDO();
        Integer newId = orderDO.getId();
        Byte deal = 1;
        customerDO.setId(orderDO.getCustomerId());
        customerDO.setDeal(deal);
        customerDao.updateByPrimaryKeySelective(customerDO);

        //添加积分
        Byte source = 0;
        PointsLogDO pointsLogDO = new PointsLogDO();
        pointsLogDO.setUid(customer.getUid());
        pointsLogDO.setPoint(orderDO.getPoints());
        pointsLogDO.setSource(source);
        pointsLogDO.setTitle(customer.getName()+"-"+customer.getAddress());
        pointsLogDO.setOrderid(newId);
        pointsLogDO.setAddtime(TimestampUtils.timestamp());
        pointsLogDao.insertSelective(pointsLogDO);
        //给合伙人添加积分
        UserDO userDOS = new UserDO();
        userDOS.setId(customer.getUid());
        userDOS.setBalance(userDO1.getBalance()+orderDO.getPoints());
        userDOS.setPoints(userDO1.getPoints()+orderDO.getPoints());
        userDao.updateByPrimaryKeySelective(userDOS);
        //查询配置(是否开启合伙人上级分成)
        if(configDO.getIsdivide() == 1){
            //查询上级推荐人
            UserDO recommond = userService.getMyRecommondUser(userDO1.getPid());
            if(recommond !=null){
                source = 2;
                Integer percent = orderDO.getPoints()*configDO.getPercent()/100;
                PointsLogDO recom = new PointsLogDO();
                recom.setOrderid(newId);
                recom.setTitle("推荐人分成获得积分");
                recom.setSource(source);
                recom.setPoint(percent);
                recom.setUid(userDO1.getPid());
                recom.setAddtime(TimestampUtils.timestamp());
                pointsLogDao.insertSelective(recom);
                //给推荐人添加积分
                UserDO userDO = new UserDO();
                userDO.setId(userDO1.getPid());
                userDO.setBalance(recommond.getBalance()+percent);
                userDO.setPoints(recommond.getPoints()+percent);
                userDao.updateByPrimaryKeySelective(userDO);
            }
        }
        return result;
    }



    /**
     * 获取下单记录列表
     * @param paging Paging
     *               uid Integer
     *               returnType  Integer
     * return LIST
     * */
    @Override
    public Map<String, Object> getDealOrderList(Paging paging, Integer uid, Integer returnType) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String,Object>> list = orderDao.getDealOrderByUid(uid);
        Page page = (Page) list;
        Object total = page.getTotal();
        allList.put("total",total);
        if(returnType == 1){
           Map<Object, List<Map<String, Object>>> timeList = JsonUtils.toMonthList(list);
            allList.put("list",timeList);
        }else{
            allList.put("list",list);
        }
        return allList;
    }

    /**
     * 获取下单记录列表
     * @param id  Integer
     * return Object
     * */
    @Override
    public DealOrderOutPutDTO getDealOrderDetail(Integer id) {
        DealOrderOutPutDTO detail = orderDao.getDealOrderBycustomerId(id);
        if(detail == null){
            throw BusinessException.of(ErrorMessageEnum.ORDER_NOTE_FOUND);
        }
        String dateFormat = "yyyy-MM-dd HH:mm:ss";
        String settime = TimestampUtils.getDateTimeOfTimestamp(Integer.parseInt(detail.getAddtime()),dateFormat);
        String addtime = TimestampUtils.getDateTimeOfTimestamp(Integer.parseInt(detail.getAddtime()),dateFormat);
        detail.setSettime(settime);
        detail.setAddtime(addtime);
        return detail;
    }


}
